package levelOrder

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func LevelOrder(root *TreeNode) [][]int {
	if root == nil {
		return [][]int{}
	}
	var res [][]int
	nodes := []*TreeNode{root}
	for len(nodes) > 0 {
		level := make([]int, 0)
		currentNodes := nodes[:]     //保存当前队列中元素
		nodes = make([]*TreeNode, 0) //存储每一层节点，使用前先清空，保证了只存储一层。
		for _, node := range currentNodes {
			level = append(level, node.Val)
			if node.Left != nil {
				nodes = append(nodes, node.Left)
			}
			if node.Right != nil {
				nodes = append(nodes, node.Right)
			}

		}
		res = append(res, level)

	}
	return res
}

var res [][]int

func LevelOrder2(root *TreeNode) [][]int {
	dfs(root, 0)
	return res
}

func dfs(root *TreeNode, level int) {
	if root == nil {
		return
	}
	if len(res) == level {
		res = append(res, []int{})
	}
	res[level] = append(res[level], root.Val)
	dfs(root.Left, level+1)
	dfs(root.Right, level+1)
}
